<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <text class="title">消息中心</text>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content" v-if="!currentConversation">
      <!-- 聊天列表 -->
      <scroll-view scroll-y class="chat-list">
        <!-- 根据当前选中的标签显示不同的列表 -->
        <template v-if="currentTab === 0">
          <!-- 好友列表 -->
          <view v-for="friend in friends" :key="friend.id" 
                class="chat-item" 
                @click="startPrivateChat(friend)">
            <view class="avatar">{{ friend.name?.[0] || 'U' }}</view>
            <view class="chat-info">
              <view class="top-line">
                <text class="name">{{ friend.name }}</text>
                <text class="time" v-if="getLastMessage(friend.id)">
                  {{ formatTime(getLastMessage(friend.id).createdAt) }}
                </text>
              </view>
              <text class="last-message" v-if="getLastMessage(friend.id)">
                {{ getLastMessage(friend.id).content }}
              </text>
            </view>
            <view class="unread" v-if="getUnreadCount(friend.id)">
              {{ getUnreadCount(friend.id) }}
            </view>
          </view>
        </template>

        <template v-else-if="currentTab === 1">
          <!-- 群聊列表 -->
          <view v-for="group in groups" :key="group.id" 
                class="chat-item" 
                @click="startGroupChat(group)">
            <view class="avatar group-avatar">{{ group.name?.[0] || 'G' }}</view>
            <view class="chat-info">
              <view class="top-line">
                <text class="name">{{ group.name }}</text>
                <text class="time" v-if="getLastGroupMessage(group.id)">
                  {{ formatTime(getLastGroupMessage(group.id).createdAt) }}
                </text>
              </view>
              <text class="last-message" v-if="getLastGroupMessage(group.id)">
                {{ getLastGroupMessage(group.id).content }}
              </text>
            </view>
            <view class="unread" v-if="getGroupUnreadCount(group.id)">
              {{ getGroupUnreadCount(group.id) }}
            </view>
          </view>
        </template>

        <template v-else-if="currentTab === 3">
          <!-- 临时会话列表 -->
          <view v-for="conv in temporaryConversations" :key="conv.id" 
                class="chat-item" 
                @click="startTemporaryChat(conv)">
            <view class="avatar temp-avatar">{{ conv.name?.[0] || 'T' }}</view>
            <view class="chat-info">
              <view class="top-line">
                <text class="name">{{ conv.name }}</text>
                <text class="time" v-if="getLastTempMessage(conv.id)">
                  {{ formatTime(getLastTempMessage(conv.id).createdAt) }}
                </text>
              </view>
              <text class="last-message" v-if="getLastTempMessage(conv.id)">
                {{ getLastTempMessage(conv.id).content }}
              </text>
            </view>
            <view class="unread" v-if="getTempUnreadCount(conv.id)">
              {{ getTempUnreadCount(conv.id) }}
            </view>
          </view>
        </template>

        <template v-else-if="currentTab === 2">
          <!-- 通知列表 -->
          <view v-for="notice in notifications" :key="notice.id" 
                class="chat-item notice-item" 
                @click="handleNotification(notice)">
            <view class="avatar notice-avatar">
              <text class="iconfont icon-notification"></text>
            </view>
            <view class="chat-info">
              <view class="top-line">
                <text class="name">{{ notice.title }}</text>
                <text class="time">{{ formatTime(notice.createdAt) }}</text>
              </view>
              <text class="last-message">{{ notice.content }}</text>
            </view>
          </view>
        </template>
      </scroll-view>
    </view>

    <!-- 聊天详情页面 -->
    <view class="chat-detail" v-if="currentConversation">
      <!-- 聊天头部 -->
      <view class="chat-header">
        <view class="back-button" @click="closeChat">
          <text class="iconfont icon-back">返回</text>
        </view>
        <view class="chat-title">
          <text>{{ currentConversation.targetUser?.name || currentConversation.title }}</text>
          <text v-if="currentConversation.targetUser?.role === 2" class="role-tag">【老师】</text>
        </view>
        <view class="header-actions">
          <text class="iconfont icon-more" @click="showMoreOptions"></text>
        </view>
      </view>

      <!-- 消息列表 -->
      <scroll-view 
        class="message-list" 
        scroll-y 
        :scroll-top="scrollTop"
        @scrolltoupper="loadMoreMessages"
        :refresher-enabled="true"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
        :id="'message-list'"
      >
        <view class="message-wrapper">
          <view v-for="(msg, index) in messages" 
                :key="index" 
                class="message-item"
                :class="{'self': msg.senderId === currentUser?.id}"
          >
            <view class="message-avatar">
              {{ msg.senderName?.[0] || 'U' }}
            </view>
            <view class="message-content">
              <view class="sender-name">
                {{ msg.senderName || '未知用户' }}
                <text v-if="msg.senderRole === 2" class="role-tag">【老师】</text>
              </view>
              
              <!-- 语音消息 -->
              <view v-if="msg.messageType === 'AUDIO'" class="audio-message" @click="playAudio(msg.content)">
                <text class="iconfont icon-voice"></text>
                <text class="audio-duration">【语音消息请在网页版查看】</text>
              </view>
              
              <!-- 文本消息 -->
              <view v-else class="text-message">
                {{ msg.content }}
              </view>
              
              <view class="message-time">{{ formatTime(msg.createdAt) }}</view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 输入区域 -->
      <view class="input-area" v-if="!isUserMuted">
        <view v-if="isRecording" class="recording-indicator">
          <text>正在录音...</text>
          <button type="warn" size="mini" @click="stopRecording">停止</button>
        </view>
        <view v-else class="input-wrapper">
          <textarea
            class="message-input"
            :value="messageInput"
            @input="handleInput"
            :adjust-position="false"
            :show-confirm-bar="false"
            :cursor-spacing="20"
            :fixed="true"
            placeholder="输入消息..."
            @confirm="sendMessage"
          ></textarea>
          <view class="input-actions">
            <button 
              class="voice-button" 
              :class="{ recording: isRecording }"
              @touchstart="startRecording"
              @touchend="stopRecording"
              @touchcancel="cancelRecording"
            >
              <text class="iconfont icon-voice"></text>
            </button>
            <button 
              class="send-button" 
              type="primary" 
              size="mini"
              @click="sendMessage"
              :disabled="!messageInput.trim()"
            >发送</button>
          </view>
        </view>
      </view>
      <view v-else class="muted-tip">
        <text>您已被禁言</text>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="tab-bar" v-if="!currentConversation">
      <view class="tab-item" :class="{ active: currentTab === 0 }" @click="currentTab = 0">
        <image class="tab-icon" src="../static/images/好友.png"></image>
        <text class="tab-text">好友</text>
        <view class="badge" v-if="unreadCounts.friends > 0">{{ unreadCounts.friends }}</view>
      </view>
      <view class="tab-item" :class="{ active: currentTab === 1 }" @click="currentTab = 1">
        <image class="tab-icon" src="../static/images/群聊.png"></image>
        <text class="tab-text">群聊</text>
        <view class="badge" v-if="unreadCounts.groups > 0">{{ unreadCounts.groups }}</view>
      </view>
      <view class="tab-item" :class="{ active: currentTab === 2 }" @click="currentTab = 2">
        <image class="tab-icon" src="../static/images/通知.png"></image>
        <text class="tab-text">通知</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentUserId: '',
      currentTab: 0,
      unreadCounts: {
        friends: 0,
        groups: 0,
        notifications: 0
      },
      friends: [],
      groups: [],
      temporaryConversations: [],
      notifications: [],
      messages: [],
      currentConversation: null,
      messageInput: '',
      isRecording: false,
      scrollTop: 0,
      oldScrollTop: 0,
      isRefreshing: false,
      lastMessages: {}, // 存储最后一条消息
      conversations: [], // 添加会话列表
      loginRequired: false, // 添加登录状态检查
      currentUser: null, // 添加当前用户信息
      socket: null, // WebSocket 实例
      participantsMap: {}, // 存储参与者信息
      hasMoreMessages: false,
      isUserMuted: false,
      currentPage: 1,
      pageSize: 20,
      audioChunks: [],
      recordingStartTime: 0,
      messageCount: 0,
    }
  },
  onLoad(options) {
    this.initialize();
    
    // 检查是否需要直接打开聊天界面
    if (options && options.directChat === 'true') {
      console.log('直接打开聊天界面:', options);
      
      // 根据传入的参数类型决定打开私聊还是群聊
      if (options.type === 'private' && options.conversationId && options.targetId) {
        // 构造好友对象
        const friend = {
          id: options.targetId,
          name: options.targetName || '好友'
        };
        
        // 构造会话对象
        const conversation = {
          id: options.conversationId,
          type: 'PRIVATE'
        };
        
        // 延迟一点执行，确保initialize完成
        setTimeout(() => {
          this.currentConversation = {
            type: 'PRIVATE',
            title: options.targetName || '好友',
            targetId: options.targetId,
            conversation: {
              id: options.conversationId,
              type: 'PRIVATE'
            }
          };
          
          // 加载消息
          this.messages = [];
          this.currentPage = 1;
          this.hasMoreMessages = true;
          this.loadMessages();
        }, 300);
      } 
      else if (options.type === 'group' && options.conversationId && options.groupId) {
        // 构造群聊对象
        const group = {
          id: options.groupId,
          name: options.groupName || '群聊',
          conversation: {
            id: options.conversationId,
            type: 'GROUP'
          }
        };
        
        // 延迟一点执行，确保initialize完成
        setTimeout(() => {
          this.currentConversation = {
            id: options.groupId,
            title: options.groupName || '群聊',
            type: 'GROUP',
            conversation: {
              id: options.conversationId,
              type: 'GROUP'
            }
          };
          
          // 加载消息
          this.messages = [];
          this.currentPage = 1;
          this.hasMoreMessages = true;
          this.loadMessages();
        }, 300);
      }
    }
  },
  methods: {
    async initialize() {
      try {
        // 检查登录状态
        let token = uni.getStorageSync('satoken');
        let userId = uni.getStorageSync('userid');
        let username = uni.getStorageSync('username');

        console.log('初始化消息中心:', { token, userId, username });
        
        if (token && userId && username) {
          this.loginRequired = false;
          // 设置基本用户信息
          const userInfo = {
            id: parseInt(userId),
            name: uni.getStorageSync('name') || username,
            username: username,
            role: parseInt(uni.getStorageSync('role')) || 1
          };
          
          this.currentUser = userInfo;
          
          // 并行加载所有数据
          try {
            await Promise.all([
              this.connectWebSocket(),
              this.fetchConversations(),
              this.fetchFriends(),
              this.fetchGroups(),
              this.fetchNotifications(),
              this.fetchTemporaryConversations()
            ]);
          } catch (error) {
            console.error('加载数据失败:', error);
            uni.showToast({
              title: '加载数据失败',
              icon: 'none'
            });
          }
        } else {
          console.log('登录信息不完整');
          this.loginRequired = true;
          uni.showToast({
            title: '请重新登录',
            icon: 'none',
            success: () => {
              setTimeout(() => {
                uni.navigateTo({
                  url: '/pages/login'
                });
              }, 1500);
            }
          });
        }
      } catch (e) {
        console.error('初始化失败', e);
        uni.showToast({
          title: '初始化失败，请重试',
          icon: 'none'
        });
      }
    },

    // 获取群聊列表
    async fetchGroups() {
      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');
        console.log('获取群聊列表...');
        
        const res = await uni.request({
          url: 'http://localhost:8080/api/chat/conversations',
          method: 'GET',
          header: {
            'satoken': token
          },
          data: {
            userId: userId
          }
        });
        
        console.log('群聊列表响应:', res);
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          // 过滤出群聊类型的会话
          this.groups = res.data.data
            .filter(conv => conv.conversation && conv.conversation.type === 'GROUP')
            .map(conv => ({
              id: conv.conversation.id,
              name: conv.title || '群聊',
              avatar: conv.group?.avatar || '/static/images/group.png',
              lastMessage: conv.lastMessage,
              conversation: conv.conversation,
              group: conv.group || {}
            }));
        } else {
          throw new Error(res.data.message || '获取群聊列表失败');
        }
      } catch (e) {
        console.error('获取群聊列表失败:', e);
        uni.showToast({
          title: '获取群聊列表失败',
          icon: 'none'
        });
      }
    },

    // 获取群聊最后一条消息
    async fetchGroupLastMessage(groupId) {
      try {
        const token = uni.getStorageSync('satoken');
        const res = await uni.request({
          url: `http://localhost:8080/api/chat/group/${groupId}/last-message`,
          method: 'GET',
          header: {
            'satoken': token
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          this.lastMessages[`group_${groupId}`] = res.data.data;
        }
      } catch (e) {
        console.error(`获取群聊 ${groupId} 最后一条消息失败:`, e);
      }
    },

    // 获取通知列表
    async fetchNotifications() {
      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');
        console.log('获取通知列表...');
        
        const res = await uni.request({
          url: 'http://localhost:8080/api/notifications/list',  // 修改为正确的API路径
          method: 'GET',
          header: {
            'satoken': token
          },
          data: {
            userId: userId
          }
        });
        
        console.log('通知列表响应:', res);
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          this.notifications = res.data.data.map(notice => ({
            ...notice,
            createdAt: new Date(notice.createTime || notice.createdAt)
          }));
        } else {
          throw new Error(res.data.message || '获取通知列表失败');
        }
      } catch (e) {
        console.error('获取通知列表失败:', e);
        uni.showToast({
          title: '获取通知列表失败',
          icon: 'none'
        });
      }
    },

    // 处理通知点击
    handleNotification(notice) {
      // 如果通知未读，标记为已读
      if (!notice.read) {
        this.markNotificationAsRead(notice.id);
      }
      
      // 根据通知类型处理点击事件
      switch (notice.type) {
        case 'FRIEND_REQUEST':
          uni.navigateTo({
            url: '/pages/friend-request?id=' + notice.id
          });
          break;
        case 'GROUP_INVITE':
          uni.navigateTo({
            url: '/pages/group-invite?id=' + notice.id
          });
          break;
        default:
          // 默认只是显示通知内容
          uni.showModal({
            title: notice.title,
            content: notice.content,
            showCancel: false
          });
      }
    },

    // 标记通知为已读
    async markNotificationAsRead(notificationId) {
      try {
        const token = uni.getStorageSync('satoken');
        await uni.request({
          url: `http://localhost:8080/api/notifications/${notificationId}/read`,
          method: 'PUT',
          header: {
            'satoken': token
          }
        });
        
        // 更新本地通知状态
        const index = this.notifications.findIndex(n => n.id === notificationId);
        if (index !== -1) {
          this.notifications[index].read = true;
        }
      } catch (e) {
        console.error('标记通知已读失败:', e);
      }
    },

    // 获取临时会话列表
    async fetchTemporaryConversations() {
      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');
        console.log('获取临时会话列表...');
        
        const res = await uni.request({
          url: 'http://localhost:8080/api/chat/conversations',  // 修改为正确的API路径
          method: 'GET',
          header: {
            'satoken': token
          },
          data: {
            userId: userId
          }
        });
        
        console.log('临时会话列表响应:', res);
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          // 过滤出临时会话（私聊类型且不是好友）
          this.temporaryConversations = res.data.data
            .filter(conv => {
              if (conv.conversation && conv.conversation.type === 'PRIVATE' && conv.targetUser) {
                // 检查是否是好友
                return !this.friends.some(friend => friend.id === conv.targetUser.id);
              }
              return false;
            })
            .map(conv => ({
              id: conv.conversation.id,
              name: conv.targetUser.name,
              avatar: conv.targetUser.avatar,
              lastMessage: conv.lastMessage
            }));
        } else {
          throw new Error(res.data.message || '获取临时会话列表失败');
        }
      } catch (e) {
        console.error('获取临时会话列表失败:', e);
        uni.showToast({
          title: '获取临时会话列表失败',
          icon: 'none'
        });
      }
    },

    // 获取临时会话最后一条消息
    async fetchTempLastMessage(convId) {
      try {
        const token = uni.getStorageSync('satoken');
        const res = await uni.request({
          url: `http://localhost:8080/api/chat/temporary/${convId}/last-message`,
          method: 'GET',
          header: {
            'satoken': token
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          this.lastMessages[`temp_${convId}`] = res.data.data;
        }
      } catch (e) {
        console.error(`获取临时会话 ${convId} 最后一条消息失败:`, e);
      }
    },

    // 添加获取存储的 cookie 方法
    getCookie(name) {
      const value = uni.getStorageSync(name);
      return value || null;
    },

    // 添加设置 cookie 方法
    setCookie(name, value, days) {
      uni.setStorageSync(name, value);
    },

    async fetchConversations() {
      try {
        const token = this.getCookie('satoken');
        console.log('Fetching conversations with token:', token);
        
        const res = await uni.request({
          url: 'http://localhost:8080/api/chat/conversations',
          method: 'GET',
          header: {
            'satoken': token
          },
          data: {
            userId: this.currentUser.id
          }
        });
        
        console.log('Conversations response:', res);
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          // 过滤掉不完整的会话数据
          this.conversations = res.data.data.filter(conv => {
            if (!conv.conversation || !conv.conversation.id || !conv.conversation.type) {
              return false;
            }
            if (conv.conversation.type === 'GROUP') {
              return conv.group && conv.group.id && conv.title;
            }
            return true;
          });

          console.log('Filtered conversations:', this.conversations);

          // 获取每个私聊会话的参与者
          for (const conv of this.conversations) {
            if (conv.conversation.type === 'PRIVATE') {
              const participantsRes = await uni.request({
                url: `http://localhost:8080/api/chat/participants/${conv.conversation.id}`,
                method: 'GET',
                header: {
                  'satoken': token
                }
              });
              if (participantsRes.statusCode === 200 && participantsRes.data.status === 10000) {
                this.participantsMap[conv.conversation.id] = participantsRes.data.data;
              }
            }
          }
        } else {
          throw new Error(res.data.message || '获取会话列表失败');
        }
      } catch (e) {
        console.error('获取会话列表失败', e);
        uni.showToast({
          title: e.message || '获取会话列表失败',
          icon: 'none'
        });
      }
    },

    async fetchFriends() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8080/api/friend/list',
          method: 'GET',
          header: {
            'satoken': uni.getStorageSync('satoken')
          },
          data: {
            userId: this.currentUser.id
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          this.friends = res.data.data;
        }
      } catch (e) {
        console.error('获取好友列表失败', e);
      }
    },

    connectWebSocket() {
      if (this.socket) {
        console.log('WebSocket 已连接，无需重复创建');
        return;
      }
      const token = uni.getStorageSync('satoken');
      if (!token) {
        console.error('无法连接WebSocket，缺少token');
        return;
      }
      
      this.socket = uni.connectSocket({
        url: `ws://localhost:8080/api/ws/chat?token=${token}`,
        success: () => {
          console.log('发起 WebSocket 连接请求成功');
        },
        fail: (err) => {
          console.error('发起 WebSocket 连接请求失败:', err);
        }
      });

      this.socket.onOpen(() => {
        console.log('WebSocket 连接已打开');
      });

      this.socket.onMessage((res) => {
        console.log('收到WebSocket消息:', res.data);
        const message = JSON.parse(res.data);
        
        if (this.currentConversation && message.conversationId === this.currentConversation.id) {
          this.messages = [...this.messages, message];
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToBottom();
            }, 300);
          });
        }
      });

      this.socket.onClose(() => {
        console.log('WebSocket 连接已关闭');
        this.socket = null; // 清理实例，以便重连
      });

      this.socket.onError((err) => {
        console.error('WebSocket 连接错误:', err);
        this.socket = null; // 清理实例
      });
    },

    handleInput(event) {
      this.messageInput = event.detail.value;
      console.log('Input event triggered. New value:', event.detail.value);
    },

    async sendMessage() {
      const messageContent = this.messageInput.trim();
      if (!messageContent) return;

      if (!this.socket || this.socket.readyState !== 1) {
        uni.showToast({
          title: '聊天服务未连接，正在重连...',
          icon: 'none'
        });
        this.connectWebSocket();
        return;
      }

      const messageData = {
        conversationId: this.currentConversation?.id || this.currentConversation?.conversation?.id,
        senderId: this.currentUser?.id,
        senderName: this.currentUser?.name,
        content: messageContent,
        messageType: 'TEXT',
        type: this.currentConversation?.type || this.currentConversation?.conversation?.type || 'PRIVATE'
      };

      // 先清空输入框
      this.messageInput = '';
      
      // 立即添加消息到列表
      const newMessage = {
        ...messageData,
        createdAt: new Date()
      };
      this.messages = [...this.messages, newMessage];
      
      // 发送消息并滚动到底部
      this.socket.send({
        data: JSON.stringify(messageData),
        success: () => {
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToBottom();
            }, 300);
          });
        },
        fail: (err) => {
          console.error('发送消息失败:', err);
          uni.showToast({
            title: '发送失败',
            icon: 'none'
          });
        }
      });
    },

    async sendAudioMessage(url, duration) {
      if (!this.socket || this.socket.readyState !== 1) {
        uni.showToast({
          title: '聊天服务未连接',
          icon: 'none'
        });
        this.connectWebSocket();
        return;
      }
      // ... (发送语音消息的逻辑也需要改成WebSocket)
    },

    async loadMessages() {
      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');

        let conversationId;
        console.log('当前会话信息:', this.currentConversation);
        
        if (this.currentConversation.type === 'GROUP') {
          conversationId = this.currentConversation.id;
        } else if (this.currentConversation.type === 'TEMPORARY' || this.currentConversation.type === 'PRIVATE') {
          conversationId = this.currentConversation?.conversation?.id;
          console.log('获取到的会话ID:', conversationId);
        }

        if (!conversationId) {
          console.error('无效的会话ID，当前会话:', this.currentConversation);
          throw new Error('无效的会话ID');
        }

        console.log('准备加载消息，会话ID:', conversationId);
        const res = await uni.request({
          url: `http://localhost:8080/api/chat/messages/${conversationId}`,
          method: 'GET',
          header: {
            'satoken': token
          },
          data: {
            userId: userId,
            page: this.currentPage - 1,
            size: this.pageSize
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          const newMessages = res.data.data.reverse();
          this.hasMoreMessages = newMessages.length === this.pageSize;
          
          if (this.currentPage === 1) {
            this.messages = newMessages;
          } else {
            this.messages = [...this.messages, ...newMessages];
          }
          
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToBottom();
            }, 300);
          });
        } else {
          throw new Error(res.data.message || '加载消息失败');
        }
      } catch (e) {
        console.error('加载消息失败:', e);
        uni.showToast({
          title: '加载消息失败',
          icon: 'none'
        });
      }
    },

    scrollToBottom() {
      const pages = getCurrentPages();
      const page = pages[pages.length - 1];
      const query = uni.createSelectorQuery().in(page);
      query.select('.message-wrapper').boundingClientRect(data => {
        if (data) {
          this.scrollTop = data.height;
        }
      }).exec();
    },

    async startPrivateChat(friend) {
      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');
        
        // 创建或获取私聊会话
        const res = await uni.request({
          url: `http://localhost:8080/api/chat/conversation/private?userId=${userId}`,
          method: 'POST',
          header: {
            'satoken': token,
            'Content-Type': 'application/json'
          },
          data: {
            targetUserId: friend.id
          }
        });

        if (res.statusCode === 200 && res.data.status === 10000) {
          const conversationData = res.data.data;
          
          this.currentConversation = {
            type: 'PRIVATE',
            title: friend.name,
            targetId: friend.id,
            conversation: conversationData.conversation
          };
          
          this.messages = [];
          this.currentPage = 1;
          this.hasMoreMessages = true;
          
          this.loadMessages();
        } else {
          throw new Error(res.data.message || '创建私聊会话失败');
        }
      } catch (e) {
        console.error('开启私聊失败:', e);
        uni.showToast({
          title: '开启私聊失败',
          icon: 'none'
        });
      }
    },
    startGroupChat(group) {
      if (!group || !group.id) {
        uni.showToast({
          title: '无效的群聊',
          icon: 'none'
        });
        return;
      }

      try {
        // 直接使用现有的会话数据
        this.currentConversation = {
          id: group.id,
          title: group.name || '群聊',
          type: 'GROUP',
          conversation: group.conversation,
          group: group.group
        };
        
        this.messages = [];
        this.currentPage = 1;
        this.hasMoreMessages = true;
        
        this.loadMessages();
      } catch (e) {
        console.error('开启群聊失败:', e);
        uni.showToast({
          title: '开启群聊失败',
          icon: 'none'
        });
      }
    },
    startTemporaryChat(conv) {
      if (!conv || !conv.id) {
        uni.showToast({
          title: '无效的临时会话',
          icon: 'none'
        });
        return;
      }

      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');
        
        console.log('开始创建临时会话，目标用户:', conv);

        // 使用私聊会话API
        uni.request({
          url: `http://localhost:8080/api/chat/conversation/private?userId=${userId}`,
          method: 'POST',
          header: {
            'satoken': token,
            'Content-Type': 'application/json'
          },
          data: {
            targetUserId: conv.targetUser?.id || conv.id
          },
          success: (res) => {
            if (res.statusCode === 200 && res.data.status === 10000) {
              const conversationData = res.data.data;
              console.log('创建临时会话成功，返回数据:', conversationData);
              
              this.currentConversation = {
                type: 'TEMPORARY',
                title: conv.name || '临时会话',
                conversation: conversationData.conversation,
                targetUser: conv.targetUser || conv
              };
              
              console.log('设置当前会话:', this.currentConversation);
              
              this.messages = [];
              this.currentPage = 1;
              this.hasMoreMessages = true;
              
              this.loadMessages();
            } else {
              console.error('创建临时会话失败:', res.data);
              throw new Error(res.data.message || '创建临时会话失败');
            }
          },
          fail: (err) => {
            console.error('开启临时会话失败:', err);
            uni.showToast({
              title: '开启临时会话失败',
              icon: 'none'
            });
          }
        });
      } catch (e) {
        console.error('开启临时会话失败:', e);
        uni.showToast({
          title: '开启临时会话失败',
          icon: 'none'
        });
      }
    },
    async fetchMessages() {
      try {
        const res = await uni.request({
          url: `/api/chat/messages/${this.currentConversation.id}`,
          method: 'GET',
          data: { userId: this.currentUserId }
        });
        if (res.data.status === 10000) {
          this.messages = res.data.data.reverse();
          this.scrollToBottom();
        }
      } catch (e) {
        console.error('获取消息失败', e);
      }
    },
    closeChat() {
      this.currentConversation = null;
      this.messages = [];
    },
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const now = new Date();
      const diff = now - date;
      
      if (diff < 60000) return '刚刚';
      if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
      if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
      
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
    },
    getLastMessage(friendId) {
      return this.lastMessages[`private_${friendId}`];
    },
    getLastGroupMessage(groupId) {
      return this.lastMessages[`group_${groupId}`];
    },
    getUnreadCount(friendId) {
      return this.unreadCounts[`private_${friendId}`] || 0;
    },
    getGroupUnreadCount(groupId) {
      return this.unreadCounts[`group_${groupId}`] || 0;
    },
    getLastTempMessage(tempId) {
      return this.lastMessages[`temp_${tempId}`];
    },
    getTempUnreadCount(tempId) {
      return this.unreadCounts[`temp_${tempId}`] || 0;
    },
    showMoreOptions() {
      // 实现更多选项功能
    },
    // 录音相关方法
    startRecording(e) {
      if (this.isRecording) return;
      
      this.isRecording = true;
      this.audioChunks = [];
      
      // 开始录音
      this.recorderManager = uni.getRecorderManager();
      
      this.recorderManager.onStart(() => {
        console.log('录音开始');
        this.recordingStartTime = Date.now();
      });
      
      this.recorderManager.onError((error) => {
        console.error('录音错误:', error);
        this.isRecording = false;
        uni.showToast({
          title: '录音失败',
          icon: 'none'
        });
      });
      
      this.recorderManager.start({
        duration: 60000, // 最长录音时间，单位ms
        sampleRate: 16000,
        numberOfChannels: 1,
        encodeBitRate: 48000,
        format: 'mp3'
      });
    },
    stopRecording() {
      if (!this.isRecording) return;
      
      this.recorderManager.stop();
      this.recorderManager.onStop(async (res) => {
        console.log('录音结束:', res);
        this.isRecording = false;
        
        // 检查录音时长
        const duration = Date.now() - this.recordingStartTime;
        if (duration < 1000) {
          uni.showToast({
            title: '录音时间太短',
            icon: 'none'
          });
          return;
        }
        
        // 上传录音文件
        try {
          const uploadRes = await uni.uploadFile({
            url: 'http://localhost:8080/api/chat/upload/audio',
            filePath: res.tempFilePath,
            name: 'file',
            header: {
              'satoken': uni.getStorageSync('satoken')
            }
          });
          
          const data = JSON.parse(uploadRes.data);
          if (data.status === 10000) {
            // 发送语音消息
            await this.sendAudioMessage(data.data.url, duration);
          } else {
            throw new Error(data.message || '上传录音失败');
          }
        } catch (e) {
          console.error('上传录音失败:', e);
          uni.showToast({
            title: '上传录音失败',
            icon: 'none'
          });
        }
      });
    },
    cancelRecording() {
      if (!this.isRecording) return;
      
      this.recorderManager.stop();
      this.isRecording = false;
    },
    playAudio(url) {
      const innerAudioContext = uni.createInnerAudioContext();
      innerAudioContext.src = url;
      innerAudioContext.play();
      
      innerAudioContext.onError((res) => {
        console.error('播放语音失败:', res);
        uni.showToast({
          title: '播放语音失败',
          icon: 'none'
        });
      });
    },
    // 加载消息历史
    async loadMoreMessages() {
      if (this.hasMoreMessages && !this.isRefreshing) {
        this.currentPage++;
        await this.loadMessages();
      }
    },
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      await this.loadMoreMessages();
      this.isRefreshing = false;
    },
    onShow() {
      // 页面显示时检查并连接WebSocket
      if (!this.socket) {
        this.connectWebSocket();
      }
    }
  },
  watch: {
    currentConversation(newVal) {
      if (newVal) {
        this.currentPage = 1;
        this.hasMoreMessages = true;
        this.messages = [];
        this.scrollTop = 0;
        this.loadMessages();
      }
    },
    messages: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToBottom();
            }, 100);
          });
        }
      },
      deep: true
    }
  },
  onUnload() {
    if (this.socket) {
      this.socket.close();
    }
  }
}
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-bar {
  height: 88rpx;
  padding-top: 44rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 15px;
  padding-right: 15px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  border-bottom: 1px solid #eee;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.main-content {
  flex: 1;
  padding-top: 132rpx;
  padding-bottom: 120rpx;
  height: calc(100vh - 232rpx);
  box-sizing: border-box;
}

.chat-list {
  height: 100%;
  padding-bottom: 100rpx;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #4a6bff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  margin-right: 20rpx;
}

.group-avatar {
  background-color: #52c41a;
}

.temp-avatar {
  background-color: #faad14;
}

.notice-avatar {
  background-color: #ff4d4f;
}

.chat-info {
  flex: 1;
  overflow: hidden;
}

.top-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.time {
  font-size: 24rpx;
  color: #999;
}

.last-message {
  font-size: 24rpx;
  color: #666;
  word-break: break-all;
  word-wrap: break-word;
  white-space: pre-wrap;
  line-height: 1.4;
  max-width: 100%;
}

.care-mode .last-message {
  font-size: 28rpx;
}

.unread {
  background-color: #ff4d4f;
  color: white;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 16rpx;
  min-width: 32rpx;
  text-align: center;
}

.chat-detail {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5;
  z-index: 999;
  display: flex;
  flex-direction: column;
}

.chat-header {
  height: 88rpx;
  padding-top: 44rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-left: 30rpx;
  padding-right: 30rpx;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 101;
  border-bottom: 1px solid #eee;
}

.back-button {
  width: 60rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
}

.chat-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
  margin: 0 20rpx;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.header-actions {
  width: 60rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.message-list {
  flex: 1;
  height: calc(100vh - 200rpx);
  box-sizing: border-box;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
}

.message-wrapper {
  padding: 20rpx;
  padding-bottom: 240rpx;
}

.message-item {
  display: flex;
  margin-bottom: 40rpx;
}

.message-item:last-child {
  margin-bottom: 20rpx;
}

.message-item.self {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #4a6bff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  margin: 0 20rpx;
}

.message-content {
  max-width: 60%;
}

.self .message-content {
  align-items: flex-end;
}

.sender-name {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.text-message {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  line-height: 1.4;
  word-break: break-all;
}

.self .text-message {
  background-color: #4a6bff;
  color: #fff;
}

.audio-message {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  min-width: 100rpx;
}

.self .audio-message {
  background-color: #4a6bff;
  color: #fff;
}

.audio-duration {
  margin-left: 10rpx;
  font-size: 24rpx;
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.loading-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 24rpx;
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f8f8f8;
  padding: 20rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #eee;
  z-index: 101;
  min-height: 120rpx;
}

.recording-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  border-radius: 10rpx;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  min-height: 80rpx;
  max-height: 160rpx;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: env(safe-area-inset-bottom);
}

.input-actions {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
}

.voice-button {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  margin-right: 20rpx;
}

.voice-button.recording {
  background-color: #4a6bff;
  color: #fff;
}

.send-button {
  background-color: #4a6bff;
  color: #fff;
  border: none;
}

.muted-tip {
  text-align: center;
  padding: 20rpx;
  color: #999;
  background-color: #f8f8f8;
  border-top: 1rpx solid #eee;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.role-tag {
  font-size: 24rpx;
  color: #4a6bff;
  margin-left: 10rpx;
}

.tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100rpx;
  background-color: #ffffff;
  border-top: 1rpx solid #eee;
  position: fixed;
  bottom: env(safe-area-inset-bottom);
  left: 0;
  right: 0;
  z-index: 100;
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  position: relative;
}

.tab-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 4px;
}

.tab-text {
  font-size: 24rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #4a6bff;
}

.badge {
  position: absolute;
  top: 0;
  right: 50%;
  transform: translateX(12rpx);
  background-color: #ff4d4f;
  color: white;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 16rpx;
  min-width: 32rpx;
  text-align: center;
}
</style>
